import { interpreter } from "@/api/request";
import { getConversationCommonMessage } from "@/api/zixun";
import type { ChatItemProps } from "@/components/Chat/chat.vue";
import { ref } from "vue";

export default function useChat() {
  let source: Array<ChatItemProps> = [];
  const chats = ref<Array<ChatItemProps>>([]);
  const chating = ref<Boolean>(false);
  const pagination = ref<{
    page: number;
    per_page: number;
    total: number;
  }>();

  const getConversationHistory = async () => {
    if (!pagination.value) {
      pagination.value = {
        per_page: 10,
        page: 1,
        total: 0
      };
    }
    const { per_page, page, total } = pagination.value;
    if (page > Math.ceil(total / per_page) && total > 0) {
      return;
    }
    const [err, res] = await interpreter(
      getConversationCommonMessage({ per_page, page })
    );
    if (!err) {
      pagination.value.page += 1;
      pagination.value.total = res.total;
      if (source.length) {
        source = res.data.concat(source);
      } else {
        source = res.data;
      }
      chats.value = source;
    }
  };

  return {
    source,
    chats,
    chating,
    getConversationHistory
  };
}
